//
//  ZClubCreateVC.m
//  WeClubs
//
//  Created by Zed Link on 28/4/2017.
//  Copyright © 2017 Zed. All rights reserved.
//

#import "ZClubCreateVC.h"
#import "ZClubDepartmentVC.h"
#import "ZEditVC.h"
#import "ZClubTypeChoseVC.h"
#import "ZResourceManager.h"

#define ChoseDescription @"点击选择"
#define InputDescription @"点击填写 (选填)"

@interface ZClubCreateVC () <UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate, ZClubTypeChoseDelegate> {
    MBProgressHUD *_hud;
    BOOL _uploadSuccess;
    NSString *_logoImageName;
}

@property (weak, nonatomic) IBOutlet UIImageView *logoImgView;
@property (weak, nonatomic) IBOutlet UIButton *createBtn;
@property (weak, nonatomic) IBOutlet UILabel *clubTypeLabel;
@property (weak, nonatomic) IBOutlet UITextField *clubNameField;
@property (weak, nonatomic) IBOutlet UILabel *sloganLabel;
@property (weak, nonatomic) IBOutlet UILabel *introductLabel;

/** 组织类型 */
@property (copy, nonatomic) NSString *clubType;
/** 组织口号 */
@property (copy, nonatomic) NSString *slogan;
/** 组织简介 */
@property (copy, nonatomic) NSString *introduct;

/** 组织类型数据源 */
@property (strong, nonatomic) NSArray <NSDictionary *> *typeDataSource;

@end

@implementation ZClubCreateVC

+ (instancetype)zNew
{
    return [self zStoryboardInstanceWithStoryboardName:@"ClubEdit"];
}

#pragma mark - About Navigation

- (void)zConfigNavigation
{
    [super zConfigNavigation];
    
    [self zAddBackItemWithGesture:YES];
    self.navigationItem.title = @"创建组织";
}

#pragma mark - View Life Cycle

- (void)zLoadSubview
{
    [super zLoadSubview];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    
    self.tableView.bounces = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.logoImgView zCornerDeal:34];
    [self.createBtn zCornerDeal:RECTANGLE_CORNER_RADIUS];
    [self setClubType:nil];
    [self setSlogan:nil];
    [self setIntroduct:nil];
    
    // 临时解决TextField中文下移问题, 去掉TextField的Border
    [self.clubNameField.subviews[0] removeFromSuperview];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _uploadSuccess = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uploadAction:) name:kDidUploadImageNotification object:nil];
}

- (void)uploadAction:(NSNotification *)notification
{
    [_hud hideAnimated:YES];
    
    NSDictionary *userInfo = notification.userInfo;
    BOOL result = [userInfo[ZNetManagerDidUploadImageNotificationStateKey] boolValue];
    
    if (result == YES) {
        UIImage *image = userInfo[ZNetManagerDidUploadImageNotificationImageKey];
        [self.logoImgView setImage:image];
        
        _logoImageName = userInfo[ZNetManagerDidUploadImageNotificationURLKey];
        [MBProgressHUD zAlertToastMessage:@"Logo上传成功"];
    } else {
        [MBProgressHUD zAlertToastMessage:@"Logo上传失败"];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSInteger existedLength = textField.text.length;
    NSInteger selectedLength = range.length;
    NSInteger replaceLength = string.length;
    NSInteger pointLength = existedLength - selectedLength + replaceLength;
    
    if (pointLength > 12) {
        return NO;
    }else{
        return YES;
    }
}

#pragma mark - Action

// 创建组织
- (IBAction)createBtnAction:(id)sender
{
    // Todo: 检查元素, 创建组织
    NSString *clubName = self.clubNameField.text;
    if (clubName.length > 12 || clubName.length < 2) {
        [MBProgressHUD zAlertToastMessage:@"请填写2至12个字符的组织名称"];
        return;
    }
    
    NSString *clubType = self.clubTypeLabel.text;
    if (clubType.length <= 0 || [clubType isEqualToString:ChoseDescription]) {
        [MBProgressHUD zAlertToastMessage:@"请选择合适的组织类型"];
        return;
    }
    
    __block NSNumber *clubTypeNumber;
    NSArray <NSDictionary *> *clubTypeArr = [ZResourceManager sharedInstance].clubType;
    [clubTypeArr enumerateObjectsUsingBlock:^(NSDictionary * dict, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([[dict objectForKey:ClubTypeNameKey] isEqualToString:self.clubType]) {
            clubTypeNumber = [dict objectForKey:ClubTypeNumberKey];
            *stop = YES;
        }
    }];
    
    
    _hud = [MBProgressHUD zAlertProgress:@"正在创建组织"];
    #warning Done

    NSDictionary *dataPara = @{
//                               @"user_id" : @([ZUserInfo sharedInstance].userId),
//                               @"token" : [ZUserInfo sharedInstance].token,
                               @"club_name" : clubName, //社团名字
                               @"avatar_url" : @"", //社团的头像地址 .可以不上传并且显示默认的头像
                               @"level" : clubTypeNumber, // 	社团的等级
//                               @"slogan" : _slogan,
//                               @"attribution" : _introduct,
                               };
    
    [HTTPRequest POST:kCreate_clubUrl parameter:dataPara success:^(id resposeObject) {
        
                 [_hud hideAnimated:YES];
        
                 NSNumber *clubId = resposeObject[@"data"][@"club_id"];
        
                 ZClubDepartmentVC *vc = [ZClubDepartmentVC zNew];
                 vc.type = ZClubDepartmentTypeCreate;
                 vc.clubId = clubId;
                 [self.navigationController pushViewController:vc animated:YES];
        
    } failure:^(NSError *error) {
        
           [_hud hideAnimated:YES];
    }];
//    [[ZNetManager sharedInstance] createNewClubWithName:clubName level:clubTypeNumber slogan:self.slogan introduct:self.introduct andAvatarURL:_logoImageName success:^(ZNetManagerStatus status, NSString *resultMsg, NSDictionary *data)
//     {
//         [_hud hideAnimated:YES];
//         
//         NSNumber *clubId = data[@"club_id"];
//         
//         ZClubDepartmentVC *vc = [ZClubDepartmentVC zNew];
//         vc.type = ZClubDepartmentTypeCreate;
//         vc.clubId = clubId;
//         [self.navigationController pushViewController:vc animated:YES];
//     } failure:^(NSString *resultMsg, NSDictionary *data)
//     {
//         [_hud hideAnimated:YES];
//         // Todo: 创建社团时, 网络错误的处理
//     }];
}

- (void)setClubType:(NSString *)clubType
{
    _clubType = clubType;
    
    if (_clubType == nil || [_clubType isEqualToString:@""]) {
        self.clubTypeLabel.text = ChoseDescription;
        self.clubTypeLabel.textAlignment = NSTextAlignmentRight;
        self.clubTypeLabel.textColor = PLACE_HOLDER_COLOR;;
    } else {
        self.clubTypeLabel.text = _clubType;
        self.clubTypeLabel.textAlignment = NSTextAlignmentLeft;
        self.clubTypeLabel.textColor = FONT_MAIN_COLOR;
    }
}

- (void)setSlogan:(NSString *)slogan
{
    _slogan = slogan;
    
    if (_slogan == nil || [_slogan isEqualToString:@""]) {
        self.sloganLabel.text = InputDescription;
        self.sloganLabel.textAlignment = NSTextAlignmentRight;
        self.sloganLabel.textColor = PLACE_HOLDER_COLOR;
    } else {
        self.sloganLabel.text = slogan;
        self.sloganLabel.textAlignment = NSTextAlignmentLeft;
        self.sloganLabel.textColor = FONT_MAIN_COLOR;
    }
}

- (void)setIntroduct:(NSString *)introduct
{
    _introduct = introduct;
    
    if (_introduct == nil || [_introduct isEqualToString:@""]) {
        self.introductLabel.text = InputDescription;
        self.introductLabel.textAlignment = NSTextAlignmentRight;
        self.introductLabel.textColor = PLACE_HOLDER_COLOR;
    } else {
        self.introductLabel.text = introduct;
        self.introductLabel.textAlignment = NSTextAlignmentLeft;
        self.introductLabel.textColor = FONT_MAIN_COLOR;
    }
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.clubNameField endEditing:YES];
    int index = (int)indexPath.section;
    
    switch (index) {
        case 1:     // 组织类型
        {
            ZClubTypeChoseVC *typeVC = [ZClubTypeChoseVC zNew];
            typeVC.delegate = self;
            [self.navigationController pushViewController:typeVC animated:YES];
        }
            break;
        case 2:     // 组织口号
        {
            ZEditVC *editVC = [ZEditVC zNew];
            [editVC setTitle:@"组织口号" andPlaceHolder:@"请输入组织口号"];
            [editVC setInputText:self.slogan];
            
            editVC.didSubmitText = ^(NSString *text) {
                [self setSlogan:text];
            };
            
            [self.navigationController pushViewController:editVC animated:YES];
        }
            break;
        case 3:     // 组织简介
        {
            ZEditVC *editVC = [ZEditVC zNew];
            [editVC setTitle:@"组织简介" andPlaceHolder:@"请输入组织简介"];
            [editVC setInputText:self.introduct];
        
            editVC.didSubmitText = ^(NSString *text) {
                [self setIntroduct:text];
            };
            
            [self.navigationController pushViewController:editVC animated:YES];
        }
            break;
        case 4:     // 组织Logo
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
                picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                picker.mediaTypes = @[@"public.image"];
                picker.delegate = self;
                picker.allowsEditing = YES;
            }
            
            [self presentViewController:picker animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [self dismissViewControllerAnimated:YES completion:^{
        _uploadSuccess = NO;
        UIImage *image = info[UIImagePickerControllerEditedImage];
        #warning TODO
//        [[ZNetManager sharedInstance] uploadImage:image named:nil];
//        _hud = [MBProgressHUD zAlertProgress:@"正在上传组织Logo"];
        [HTTPRequest uploadImage:image named:nil success:^(id resposeObject) {
            ZLog(@"success:%@",resposeObject);
        } failure:^(NSError *error) {
            
        }];
    }];
}

#pragma mark - ZClubTypeChoseDelegate

- (void)clubTypeChoseControllerdidSelectClubType:(NSString *)clubType
{
    [self setClubType:clubType];
}

#pragma mark - Getter & Setter

- (NSArray *)typeDataSource
{
    if (_typeDataSource == nil) {
        _typeDataSource = [ZResourceManager sharedInstance].clubType;
    }
    return _typeDataSource;
}

@end
